//
//  NetWorkTools.swift
//  Weibo
//
//  Created by 赵志文 on 15/11/23.
//  Copyright © 2015年 zzw. All rights reserved.
//  网络工具类

/**
App Key：1135921741
App Secret：d077f7b2680c0c1203ed54a371307933
创建时间：2015-03-02
应用地址：http://www.itheima.com
https://api.weibo.com/oauth2/authorize
*/
import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetWorkTools: AFHTTPSessionManager {
    
    private let clientId = "1135921741"
    private let clientSecret = "d077f7b2680c0c1203ed54a371307933"
    //回调地址
    let redirectUri = "http://www.itheima.com"
    
    /// 单例
    static let sharedTools: NetWorkTools = {
        
        // 指定 baseURL
        var instance = NetWorkTools(baseURL: nil)
        
        // 设置反序列化的支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    var oauthUrl :NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    //MARK:获取token
    /// 获取token
    ///
    /// - parameter code:
    ///
    /// - returns: RACSingle
    func loadAccessToken(code:String) -> RACSignal{
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": clientId,
            "client_secret": clientSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        return request(.POST, URLString: urlString, parameters: params)
    }
    
    //MARK:获取用户信息
    /// 获取用户信息
    ///
    /// - parameter uid:        uid
    /// - parameter accesToken:access_token
    ///
    /// - returns: RACSingle
    /// - see[]()
    func loadUserInfo(uid:String, accesToken:String)->RACSignal{
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parms = ["access_token":accesToken, "uid":uid]
        
        return request(.GET, URLString: urlString, parameters: parms)
    }
    

    //MARK:私有方法
    /// 网络请求方法
    ///
    /// - parameter method:     method
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    ///
    /// - returns: RAC Signal
    func request(method: RequestMethod, URLString: String, parameters: [String: AnyObject]?) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            // 1. 成功的回调闭包
            let successCallBack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
                // 将结果发送给订阅者
                subscriber.sendNext(result)
                // 完成
                subscriber.sendCompleted()
            }
            
            // 2. 失败的回调闭包
            let failureCallBack = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
                print(error)
                subscriber.sendError(error)
            }
            
            // 3. 根据方法，选择调用不同的网络方法
            // if method == RequestMethod.GET {
            if method == .GET {
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            } else {
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
            
            return nil
        })
    }

}
